package com.hsd.voice_asr.utils;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-04-14 13:49:43
 */
public class SocketUtil {

    private static Map<String, SocketChannel> socketControlMap=new ConcurrentHashMap<>();
    private static Map<String, Socket> socketMap=new ConcurrentHashMap<>();

    public static void addSocketControl(String deviceKey,SocketChannel socketChannel){
        socketControlMap.put(deviceKey, socketChannel);
    }
    public static void addSocket(String deviceKey,Socket socket){
        socketMap.put(deviceKey, socket);
    }
    public static void removeSocketChannel(String deviceKey){
        try {
            SocketChannel socketChannel=socketControlMap.remove(deviceKey);
            if(socketChannel!=null) socketChannel.close();
            Socket socket = socketMap.remove(deviceKey);
            if (socket != null) socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void removeSocket(String deviceKey){
        socketMap.remove(deviceKey);
    }

    public static void sendMessage(SocketChannel socketChannel, String message) throws IOException{
        byte[] bytes = message.getBytes("UTF-8");
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        socketChannel.write(buffer);
    }

    public static void startMeeting(String deviceKey) throws IOException{
        SocketChannel socketChannel = socketControlMap.get(deviceKey);
        do {
            sendMessage(socketChannel, "ACKSTART||START_SESSION||ACKEND");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (socketMap.get(deviceKey) == null);
    }

    public static void endMeeting(String deviceKey) throws IOException{
        do {
            SocketChannel socketChannel=socketControlMap.remove(deviceKey);
            sendMessage(socketChannel, "ACKSTART||END_SESSION||ACKEND");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (socketMap.get(deviceKey) != null);
    }

}
